<template>
  <div class="materialAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave(materialFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item name="1" class="transform-down">
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title"
            >{{
              pageType !== "detail"
                ? pageType === "add"
                  ? "新增"
                  : "编辑"
                : ""
            }}无人机{{ pageType == "detail" ? "详情" : "" }}</span
          >
        </template>
        <div class="material-info">
          <el-form
            :model="materialForm"
            ref="materialFormRef"
            :rules="queryRules"
            label-width="120"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="无人机品牌:" prop="droneBrand">
                  <el-input
                    v-model="materialForm.droneBrand"
                    placeholder="请输入"
                    clearable
                    maxlength="40"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="无人机型号:" prop="droneType">
                  <el-input
                    ref="refInput"
                    v-model="materialForm.droneType"
                    placeholder="请输入"
                    clearable
                    maxlength="40"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="无人机SN:" prop="droneSerialNumber">
                  <el-input
                    v-model="materialForm.droneSerialNumber"
                    placeholder="请输入"
                    clearable
                    maxlength="40"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="采购时间"
                  prop="purchaseTime"
                  label-width="134"
                >
                  <el-date-picker
                    v-model="materialForm.purchaseTime"
                    format="YYYY/MM/DD"
                    class="search-input"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item
                  label="卫星导航系统:"
                  prop="satelliteNavigationSystem"
                >
                  <el-input
                    v-model="materialForm.satelliteNavigationSystem"
                    placeholder="请输入"
                    clearable
                    maxlength="40"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item
                  label="无人机技术参数:"
                  prop="technicalParameters"
                >
                  <el-input
                    v-model="materialForm.technicalParameters"
                    placeholder="请输入"
                    clearable
                    maxlength="50"
                    class="search-input"
                    style="width: 1500px"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="是否解禁" prop="banFlag">
                  <el-select
                    v-model="materialForm.banFlag"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in stockTypeList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="materialForm.banFlag == 0">
                <el-form-item label="解禁到期时间:" prop="banTime">
                  <el-date-picker
                    v-model="materialForm.banTime"
                    format="YYYY/MM/DD"
                    class="search-input"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="是否装4G模块:" prop="netModuleFlag">
                  <el-select
                    v-model="materialForm.netModuleFlag"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in stockTypeList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="归属部门:"
                  prop="belongDepartment"
                  label-width="134"
                >
                  <el-select
                    ref="refSelect"
                    v-model="materialForm.belongDepartment"
                    placeholder="请选择归属部门"
                    clearable
                    class="search-input"
                  >
                    <!-- @change="handleDepart" -->
                    <el-option
                      v-for="dict in deptList"
                      :key="dict.deptId"
                      :label="dict.deptName"
                      :value="dict.deptId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注:" prop="remark">
                  <el-input
                    style="width: 100%"
                    v-model="materialForm.remark"
                    type="textarea"
                    maxlength="2000"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="解禁文件上传:">
                  <Upload
                    :fileList="materialForm.banFile"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    :limit="10"
                    accept=".doc,.docx,.pdf,.jpg,.png"
                    @success="(result) => uploadSuccess(result)"
                    @deleteFile="(result) => uploadRemove(result)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import Upload from "@/components/Upload/index";
import { getDictsApi } from "@/api/dict";
import { deptTreeSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getdronemodifyApi,
  getdronedetailApi,
  getDeptListApi,
} from "@/api/operation/productLibrary.js";
const emit = defineEmits([
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
  FormTemplate: {
    type: Object,
    default: {},
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 物料表单引用
const materialFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 单位列表
const unitList = ref([]);
// 是否字典
const stockTypeList = ref([]);
// 供应商列表
const suppliereList = ref([]);
// 默认税率列表
const taxRateList = ref([]);
// 销售单价初始值
const purchasePrice = ref(null);
// 部门列表
const deptList = ref([]);

// // 物料表单数据模板
const materialFormTemplate = { banFile: [] };
const data = reactive({
  // 物料表单
  materialForm: JSON.parse(JSON.stringify(materialFormTemplate)),
  // 物料表单校验规则
  queryRules: {
    droneBrand: [
      { required: true, message: "请输入无人机品牌", trigger: "blur" },
    ],
    droneType: [
      { required: true, message: "请输入无人机型号", trigger: "blur" },
    ],
    droneSerialNumber: [
      { required: true, message: "请输入无人机SN", trigger: "blur" },
    ],
    purchaseTime: [
      { required: true, message: "请输入采购时间", trigger: "blur" },
    ],
    satelliteNavigationSystem: [
      { max: 39, message: "最大可输入40字符", trigger: "blur" },
    ],
    technicalParameters: [
      { max: 49, message: "最大可输入50字符", trigger: "blur" },
    ],
    remark: [{ max: 49, message: "最大可输入50字符", trigger: "blur" }],
  },

  flagList: [
    {
      label: "是",
      value: 1,
    },
    {
      label: "否",
      value: 0,
    },
  ],
  classOptions: [],
});
const { materialForm, queryRules, flagList, classOptions } = toRefs(data);

watch(
  () => props.FormTemplate,
  (newValue, oldValue) => {
    materialForm.value = JSON.parse(JSON.stringify(newValue));
  },
  { deep: true }
);

/**
 * @description: 保存
 * @param {Object} materialFormRef 物料表单引用
 */
const handleAddSave = async (materialFormRef) => {
  if (!materialFormRef) return;
  await materialFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          materialForm.value.status = 0;
          const res = await getdronemodifyApi(materialForm.value);
          if (res.code === 200) {
            emit("update:productLibraryAddShow", false);
            emit("refreshList", true);
            ElMessage.success(res.msg);
            materialForm.value = JSON.parse(
              JSON.stringify(materialFormTemplate)
            );
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  materialForm.value.banFile.push({ ...response, businessType: 4 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  materialForm.value.banFile.splice(index, 1);
}

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("update:productLibraryAddShow", false);
    materialForm.value = JSON.parse(JSON.stringify(materialFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:productLibraryAddShow", false);
        materialForm.value = JSON.parse(JSON.stringify(materialFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("erp_warehousing").then((res) => {
    // 审核状态
    if (res.code === 200) {
      stockTypeList.value = res.data;
    }
  });
  // 运维部门列表
  await getDeptListApi(107).then((res) => {
    if (res.code === 200) {
      deptList.value = res.data;
      // nextTick(() => {
      //   refSelect.value.focus(); // 聚焦
      // });
    }
  });
}

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (droneId) => {
  try {
    detailInfoShow.value = true;
    const res = await getdronedetailApi(droneId);
    materialForm.value = res.data;
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 处理供应商、生产厂家选择
 */
const handleSuppliereSelect = (value, type) => {
  switch (type) {
    case 1:
      materialForm.value.supplierId = value.supplierId;
      break;
    case 2:
      materialForm.value.manufacturerId = value.supplierId;
      break;
    default:
      break;
  }
};

onMounted(() => {
  getDicts();
  nextTick(() => {
    refInput.value.focus(); // 聚焦
  });
});

const querySearch = (queryString, cb) => {
  const results = queryString
    ? suppliereList.value.filter(createFilter(queryString))
    : suppliereList.value;
  cb(results);
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

defineExpose({
  handleDetailInfo,
});
</script>
<style>
.autocomplete-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
<style lang="scss" scoped>
.materialAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .el-collapse,
  .el-collapse-item__wrap {
    border: none;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }
  .material-info {
    padding: 20px 10px 5px 10px;
    background-color: #fafafa;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
    .table-operate {
      display: flex;
      justify-content: space-around;
      .table-icon {
        width: 20px;
        height: 20px;
        cursor: pointer;
      }
    }
  }
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}
.auto-item {
  width: 125px;
  text-align: center;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
</style>
